package org.jfsm.demo.calculator;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.jfsm.core.FSMException;
import org.jfsm.log.StreamLogger;

@SuppressWarnings("serial")
public class CalcDemo extends JFrame {

    CalcController controller = new CalcController();
    JTextField display;

    private void keyAction(String cmd) {
        controller.dispatcher.key.dispatch(controller.ctx, cmd.charAt(0));
        display.setText(String.valueOf(controller.ctx.display));
    }

    public CalcDemo() throws FSMException {

        JPanel pFrame = new JPanel();
        pFrame.setLayout(new FlowLayout());

        display = new JTextField("0");
        display.setHorizontalAlignment(JTextField.RIGHT);
        display.setEditable(false);

        JPanel pCalc = new JPanel();
        pCalc.setLayout(new BorderLayout(0, 10));
        pCalc.add("North", display);

        pFrame.add("Center", pCalc);

        Dimension dSize = pCalc.getPreferredSize();
        dSize.width = dSize.width + 20;
        dSize.height = dSize.height + 20;
        pFrame.setSize(dSize);

        JPanel pKey = new JPanel();
        pKey.setLayout(new GridLayout(4, 4, 5, 5));
        add("Center", pKey);

        String[] buttons = { //
        //
                "7", "8", "9", "/", //
                "4", "5", "6", "*", //
                "1", "2", "3", "-", //
                "0", "Del", "=", "+" //
        };

        for (String key : buttons) {
            JButton b = new JButton(key);
            pKey.add(b);
            b.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    keyAction(e.getActionCommand());
                }
            });
        }

        pCalc.add("South", pKey);

        setLayout(new BorderLayout(0, 0));
        add("North", pFrame);
        setBackground(Color.darkGray);

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    public static void main(String args[]) throws Exception {
        new StreamLogger(System.out, true).setAsDefault();
        CalcDemo calc = new CalcDemo();
        calc.setTitle("SimpleFSM demo");
        calc.pack();
        calc.setLocation(400, 250);
        calc.setVisible(true);
        calc.setResizable(false);
    }
}